package com.apes.framework.plugin.fsm;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.outbox.annotation.OutBoxExclude;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Date;

/**
 * 功能：状态实例任务
 *
 * @author xul
 * @create 2020-08-27 11:37
 */
@OutBoxExclude
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = FsmStateInstanceTask.CONST_TABLE_NAME, indexes = {
        @Index(columnList = "fsm_state_instance_id"), @Index(columnList = "next_time, finished")})
public class FsmStateInstanceTask extends Model {
    public static final String CONST_TABLE_NAME = "fsm_state_inst_task";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "状态流：状态实例任务", padding = 12)
    @Comment("编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "state_id", referencedColumnName = "id", nullable = false)
    @Comment("状态")
    private FsmState state;

    @Column(name = "task_id", length = 60, nullable = false)
    @Comment("任务Id")
    private String taskId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fsm_state_instance_id", referencedColumnName = "id", nullable = false)
    @Comment("状态实例")
    private FsmStateInstance fsmStateInstance;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fsm_flow_instance_id", referencedColumnName = "id", nullable = false)
    @Comment("状态流实例")
    private FsmFlowInstance fsmFlowInstance;

    @Column(name = "finished", columnDefinition = "number(1,0) default 0", nullable = false)
    @Comment("是否结束")
    private boolean finished = false;

    @Column(name = "delay")
    @Comment("间隔")
    private int delay;

    @Column(name = "repeat")
    @Comment("重复次数")
    private int repeat;

    @Column(name = "timeUnit")
    @Comment("时间单位")
    private int timeUnit;

    @Column(name = "algorithm", length = 32)
    @Comment("时间算法")
    private String algorithm;

    @Column(name = "next_time")
    @Comment("下一次执行时间")
    private Date nextTime;

    @Column(name = "times")
    @Comment("执行次数")
    private int times = 0;

    @Column(name = "params", length = 512)
    @Comment("执行参数")
    private String params;

    @Column(name = "action_expr", length = 250)
    @Comment("动作表达式")
    private String actionExpr;

    public void incTimes() {
        this.times += 1;
    }
}
